<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<title>修改应用 | STAT HUB</title>
	<link type="text/css" rel="stylesheet" href="resource/css/framework.css" />
	<link type="text/css" rel="stylesheet" href="resource/css/main.css" />
	<link type="text/css" rel="stylesheet" href="resource/css/jquery.alerts.css" media="screen" />
	<script type="text/javascript" src="resource/javascript/jquery.min.js"></script>
	<script type="text/javascript" src="resource/javascript/jquery-ui.min.js"></script>
	<script type="text/javascript" src="resource/javascript/jquery.alerts.js"></script>
	<script type="text/javascript" src="resource/javascript/stathub.js"></script>
	<style type="text/css">
		.repeat {
			height:48px;
		}
		.ui.form .ui.input .full-width {
			width:450px;
		}
		.ui.form .ui.input .part-width {
			width:430px;
		}
		.ui.form .ui.input .half-width {
			width:207px;
		}
		.ui.form .ui.input {
			width:550px;
		}
	</style>
</head>
<body>
	<div class="page">
		<!--header begin-->
		<header>
			<div class="bigcontainer">
				<div id="logo">
					<a href="/">STAT HUB 应用管理</a>
				</div>
				<div class="user">
					<div class="ui compact notif menu">
						<a class="item" href="notifications.html">
							<i class="mail large icon"></i>
							<span id="message_count" class="circular floating ui small red label"></span>
						</a>
					</div>
					<div class="ui icon top right dropdown">
						<a href="user_profile.html">
							<img class="ui avatar image" src="resource/images/avatar-default.gif"/>
							欢迎，管理员
						</a>
					</div>
				</div>
			</div>
		</header>
		<!-- the main menu-->
		<div class="ui teal inverted menu">
			<div class="bigcontainer">
				<div class="right menu">
					<a class="item" href="/"><i class="home icon"></i>管理首页</a>
					<a class="item" href="node_list.html"><i class="sitemap icon"></i>节点</a>
					<a class="active item" href="app_list.html"><i class="cloud icon"></i>应用</a>
					<a class="item" href="help.html"><i class="help icon"></i>帮助</a>
					<a class="item" href="api_doc.html"><i class="info icon"></i>API接口</a>
				</div>
			</div>
		</div>
		<!--the main content begin-->
		<div class="container">
			<!--the content-->
			<div class="ui grid">
				<!--the vertical menu-->
				<div class="four wide column">
					<div class="verticalMenu">
						<div class="ui vertical pointing menu fluid">
							<a class="item" href="./new_app.html">
								<i class="rocket icon"></i> 部署新应用
							</a>
							<a class="active teal item" href="app_list.html">
								<i class="cloud icon"></i> 所有应用
							</a>
							<a class="item" href="app_stat.html">
								<i class="bar chart icon"></i> 应用统计
							</a>
						</div>
					</div>
				</div>
				<!--the App list-->
				<div class="twelve wide column">
					<div class="pageHeader">
						<div class="segment">
							<h3 class="ui dividing header">
								<i class="large edit icon"></i>
								<div class="content">
									修改应用
									<div class="sub header">输入新的应用信息</div>
								</div>
							</h3>
						</div>
					</div>
					<div class="ui form fluid vertical segment">
						<form id="f" name="f" method="post">
							<input type="hidden" name="start" value="true" id="start"/>
							<!-- element -->
							<div class="field">
								<label>应用名称</label>
								<div class="ui small left icon input">
									<input type="text" name="name" id="name" class="full-width" placeholder="应用名称包含中文、英文、数字字符，不能包含'.'、'*'等特殊字符">
									<i class="cloud icon"></i>
								</div>
							</div>
							<div class="field">
								<label>进程</label>
								<div class="ui small left icon input">
									<input type="text" name="toProcess" id="toProcess" class="full-width" placeholder="必须填写">
									<i class="code icon"></i>
								</div>
							</div>
							<div class="field">
								<label>工作目录</label>
								<div class="ui small left icon input">
									<input type="text" name="workingDirectory" id="workingDirectory" class="full-width">
									<i class="folder icon"></i>
								</div>
							</div>
							<div class="field">
								<label>运行参数 <a href="javascript:void(0)" onclick="add_arg('')"><img src="images/add.gif" align="absmiddle"></a></label>
								<div id="args"></div>
							</div>
							<div class="field">
								<label>环境变量 <a href="javascript:void(0)" onclick="add_env('', '')"><img src="images/add.gif" align="absmiddle"></a></label>
								<div id="envs"></div>
							</div>
							<div class="field">
								<label>退出信号</label>
								<div class="ui small left input">
									<select name="killSignal" id="killSignal" class="form-control full-width">
										<option value="1"> 1 - HUP (hang up)</option>
										<option value="2"> 2 - INT (interrupt)</option>
										<option value="3"> 3 - QUIT (quit)</option>
										<option value="6"> 6 - ABRT (abort)</option>
										<option value="9"> 9 - KILL (non-catchable, non-ignorable kill)</option>
										<option value="14">14 - ALRM (alarm clock)</option>
										<option value="15" selected>15 - TERM (software termination signal)</option>
									</select>
								</div>
							</div>
							<div class="field">
								<label>端口</label>
								<div class="ui small left input">
									<input type="text" name="ports" id="ports" class="full-width" placeholder="逗号分隔，'0'表示随机端口" value="0,0">
								</div>
							</div>
							<div class="field">
								<label>下载地址 <a href="javascript:void(0)" onclick="add_uri('')"><img src="images/add.gif" align="absmiddle"></a></label>
								<div id="uris"></div>
							</div>
							<div class="field">
								<label>分配资源</label>
								<div class="ui small left input">
									<select name="resAlloc" id="resAlloc" class="form-control full-width">
										<option value="1">分配</option>
										<option value="0" selected>不分配</option>
									</select>
								</div>
							</div>
							<div id="resAllocs" class="hidden">
								<div class="field">
									<label>CPU核数量</label>
									<div class="ui small left input">
										<div class="ui small left input">
											<input name="resAlloc_cpus" id="resAlloc_cpus" class="full-width" type="text" value="0.1">
										</div>
									</div>
								</div>
								<div class="field">
									<label>内存（MB）</label>
									<div class="ui small left input">
										<div class="ui small left input">
											<input name="resAlloc_mem" id="resAlloc_mem" class="full-width" type="text" value="512">
										</div>
									</div>
								</div>
								<div class="field">
									<label>磁盘空间（MB）</label>
									<div class="ui small left input">
										<div class="ui small left input">
											<input name="resAlloc_disk" id="resAlloc_disk" class="full-width" type="text" value="1024">
										</div>
									</div>
								</div>
							</div>
							<div class="field">
								<label>健康检查</label>
								<div class="ui small left input">
									<select name="healthCheck" id="healthCheck" class="form-control full-width">
										<option value="1">开启</option>
										<option value="0" selected>关闭</option>
									</select>
								</div>
							</div>
							<div id="healthChecks" class="hidden">
								<div class="field">
									<label>初始延时（秒）</label>
									<div class="ui small left input">
										<div class="ui small left input">
											<input name="healthCheck_initialDelaySeconds" id="healthCheck_initialDelaySeconds" class="full-width" type="text" value="60">
										</div>
									</div>
								</div>
								<div class="field">
									<label>检查间隔（秒）</label>
									<div class="ui small left input">
										<div class="ui small left input">
											<input name="healthCheck_intervalSeconds" id="healthCheck_intervalSeconds" class="full-width" type="text" value="20">
										</div>
									</div>
								</div>
								<div class="field">
									<label>协议</label>
									<div class="ui small left input">
										<select name="healthCheck_protocol" id="healthCheck_protocol" class="form-control full-width">
											<option value="HTTP" selected>HTTP</option>
											<option value="HTTPS">HTTPS</option>
										</select>
									</div>
								</div>
								<div class="field">
									<label>访问路径</label>
									<div class="ui small left input">
										<div class="ui small left input">
											<input name="healthCheck_path" id="healthCheck_path" class="full-width" type="text" value="/">
										</div>
									</div>
								</div>
								<div class="field">
									<label>端口序号</label>
									<div class="ui small left input">
										<div class="ui small left input">
											<input name="healthCheck_portIndex" id="healthCheck_portIndex" class="full-width" type="text" value="0">
										</div>
									</div>
								</div>
								<div class="field">
									<label>超时时间（秒）</label>
									<div class="ui small left input">
										<div class="ui small left input">
											<input name="healthCheck_timeoutSeconds" id="healthCheck_timeoutSeconds" class="full-width" type="text" value="20">
										</div>
									</div>
								</div>
								<div class="field">
									<label>允许的连续失败次数</label>
									<div class="ui small left input">
										<div class="ui small left input">
											<input name="healthCheck_maxConsecutiveFailures" id="healthCheck_maxConsecutiveFailures" class="full-width" type="text" value="3">
										</div>
									</div>
								</div>
							</div>
							<input name="save" id="save" class="ui small blue submit button" type="button" value="立即保存">
						</form>
					</div>
				</div>
			</div>
		</div>	
	</div>
	<!--footer begin-->
	<footer>
		<div id="copyrights">
			<div class="inset">
				<div class="bigcontainer">
					<div class="fl">
						<div class="logo"></div>
						<p>&copy; 2014 lane.cn@gmail.com <a href="https://github.com/lane-cn/stat" target="_blank">https://github.com/lane-cn/stat</a></p>
					</div>
				</div>
			</div>
		</div>
	</footer>
	<script>
	$(document).ready(function() {
		var name = requestParameter('name').name.replace('#', '');
		$.get('/v1/app/' + name, function(app, status, xhr) {
			show_app(app);
		});
		
		$('#healthCheck').change(function(sel) {
			var show = parseInt(sel.target.value);
			if (show) {
				$('#healthChecks').show();
			} else {
				$('#healthChecks').hide();
			}
		});
		
		$('#resAlloc').change(function(sel) {
			var show = parseInt(sel.target.value);
			if (show) {
				$('#resAllocs').show();
			} else {
				$('#resAllocs').hide();
			}
		});
		
		$('#save').click(function() {
			save_app();
		});
	});
	
	function show_app(app) {
		//edit satatus
		$('#name').attr("disabled","disabled")
		
		//display data
		$('#start').val(app.start);
		$('#name').val(app.name);
		$('#toProcess').val(app.toProcess);
		$('#workingDirectory').val(app.workingDirectory);
		if (app.args) {
			$.each(app.args, function(i, arg) {
				add_arg(arg);
			});
		}
		if (app.envs) {
			$.each(app.envs, function(k, v) {
				add_env(k, v);
			});
		}
		if (app.uris) {
			$.each(app.uris, function(i, uri) {
				add_uri(uri);
			});
		}
		$('#killSignal').val(app.killSignal);
		$('#ports').val(app.ports);
		
		if (app.resAlloc) {
			show_res_alloc(app.resAlloc);
			$('#resAlloc').val('1');
			$('#resAllocs').show();
		} else {
			$('#resAlloc').val('0');
			$('#resAllocs').hide();
		}
		
		if (app.healthChecks && app.healthChecks.length > 0) {
			show_health_check(app.healthChecks[0]);
			$('#healthCheck').val('1');
			$('#healthChecks').show();
		} else {
			$('#healthCheck').val('0');
			$('#healthChecks').hide();
		}
	}
	
	function show_res_alloc(resAlloc) {
		$('#resAlloc_cpus').val(resAlloc.cpus);
		$('#resAlloc_mem').val(resAlloc.mem / 1024 / 1024);
		$('#resAlloc_disk').val(resAlloc.disk / 1024 / 1024);
	}
	
	function show_health_check(healthCheck) {
		$('#healthCheck_initialDelaySeconds').val(healthCheck.initialDelaySeconds);
		$('#healthCheck_intervalSeconds').val(healthCheck.intervalSeconds);
		$('#healthCheck_protocol').val(healthCheck.protocol);
		$('#healthCheck_path').val(healthCheck.path);
		$('#healthCheck_portIndex').val(healthCheck.portIndex);
		$('#healthCheck_timeoutSeconds').val(healthCheck.timeoutSeconds);
		$('#healthCheck_maxConsecutiveFailures').val(healthCheck.maxConsecutiveFailures);
	}
	
	function save_app() {
		var name = $('#name').val();
		var start = $('#start').val() == 'true';
		var toProcess = $('#toProcess').val();
		var workingDirectory = $('#workingDirectory').val();
		var killSignal = parseInt($('#killSignal').val());
		var ports = get_ports($('#ports').val());
		var args = get_list('args', 'arg');
		var uris = get_list('uris', 'uri');
		var envs = get_map('envs', 'envName', 'envValue');
		var resAlloc = get_res_alloc();
		var health_checks = get_health_checks();
		var app = {
			name: name,
			start: start,
			toProcess: toProcess,
			workingDirectory: workingDirectory,
			envs: envs,
			args: args,
			ports: ports,
			uris: uris,
			killSignal: killSignal,
			resAlloc: resAlloc,
			healthChecks: health_checks
		};
		var json = JSON.stringify(app);
		$.ajax({
			url: '/v1/app/' + app.name,
			type: 'PUT',
			contentType: 'application/json',
			data: json,
			dataType: 'json',
			success: function(data, status, xhr) {
				jAlert('已经保存', '提示');
				$('#popup_ok').click(function() {
					window.location.href = 'app.html?name=' + name;
				});
			},
			error: function(xhr, status, error) {
				jAlert('保存失败，状态：' + error + ', 信息: ' + xhr.responseJSON.message, '错误');
			}
		});
	}

	function get_res_alloc() {
		var show = $('#resAlloc').val();
		if (show == '1') {
			var cpus = $('#resAlloc_cpus').val();
			var mem = new Number($('#resAlloc_mem').val());
			var disk = new Number($('#resAlloc_disk').val());
			return {
				cpus: cpus,
				mem: mem * 1024 * 1024,
				disk: disk * 1024 * 1024
			};
		} else {
			return null;
		}
	}

	function get_health_checks() {
		var r = new Array();
		var show = $('#healthCheck').val();
		if (show == '1') {
			var initialDelaySeconds = $('#healthCheck_initialDelaySeconds').val();
			var intervalSeconds = $('#healthCheck_intervalSeconds').val();
			var protocol = $('#healthCheck_protocol').val();
			var path = $('#healthCheck_path').val();
			var portIndex = $('#healthCheck_portIndex').val();
			var timeoutSeconds = $('#healthCheck_timeoutSeconds').val();
			var maxConsecutiveFailures = $('#healthCheck_maxConsecutiveFailures').val();
			
			r.push({
				initialDelaySeconds: initialDelaySeconds,
				intervalSeconds: intervalSeconds,
				protocol: protocol,
				path: path,
				portIndex: portIndex,
				timeoutSeconds: timeoutSeconds,
				maxConsecutiveFailures: maxConsecutiveFailures
			});
		}
		return r;
	}

	function get_map(panelId, keyId, valueId) {
		var map = new Object();
		var keys = get_list(panelId, keyId);
		var values = get_list(panelId, valueId);
		if (keys) {
			for (var i=0; i<keys.length; i++) {
				map[keys[i]] = values[i];
			}
		}
		return map;
	}
	
	function get_list(panelId, ctlId) {
		var list = $('#' + panelId + ' input[type="text"]');
		var r = new Array();
		for (var i=0; i<list.length; i++) {
			if (list[i].id == ctlId) {
				r.push(list[i].value);
			}
		}
		return r;
	}
	
	function get_ports(s) {
		var p = new Array();
		if (s) {
			var ary = s.split(',');
			if (ary != null) {
				for (var i=0; i<ary.length; i++) {
					p.push(parseInt(ary[i]));
				}
			}
		}
		return p;
	}
	
	function add_arg(val) {
		var max = 0;
		var es = $('#args').children();
		for (var i = 0; i < es.length; i ++) {
			var id = parseInt(es[i].id.split('_')[1]);
			if (id > max) {
			max = id;
			}
		}
		var id = "arg_" + (max+1);
		var div = '<div id="' + id + '" class="ui small left input repeat">'
		div += '<input type="text" name="arg" id="arg" class="part-width" value="' + val + '"/> ';
		div += '<a href="javascript:void(0)" onclick="remove(\'' + id + '\')"><img src="images/11-16.png" align="absmiddle"/></a>';
		div += '</div>';
		$('#args').append(div);
	}
	
	function add_env(name, val) {
		var max = 0;
		var es = $('#envs').children();
		for (var i = 0; i < es.length; i ++) {
		var id = parseInt(es[i].id.split('_')[1]);
		if (id > max) {
			max = id;
		}
		}
		var id = "env_" + (max+1);
		var div = '<div id="' + id + '" class="ui small left input repeat">';
		div += '<input type="text" name="envName" id="envName" class="half-width" value="' + name + '"/>';
		div += ' = ';
		div += '<input type="text" name="envValue" id="envValue" class="half-width" value="' + val + '"/> ';
		div += '<a href="javascript:void(0)" onclick="remove(\'' + id + '\')"><img src="images/11-16.png" align="absmiddle"/></a>';
		div += '</div>';
		$('#envs').append(div);
	}
	
	function add_uri(val) {
		var max = 0;
		var es = $('#uris').children();
		for (var i = 0; i < es.length; i ++) {
			var id = parseInt(es[i].id.split('_')[1]);
			if (id > max) {
				max = id;
			}
		}
		var id = "uri_" + (max+1);
		var div = '<div id="' + id + '" class="ui small left input repeat">'
		div += '<input type="text" name="uri" class="part-width" id="uri" value="' + val + '"/> ';
		div += '<a href="javascript:void(0)" onclick="remove(\'' + id + '\')"><img src="images/11-16.png" align="absmiddle"/></a>';
		div += '</div>';
		$('#uris').append(div);
	}
	
	function remove(id) {
		$('#' + id).remove();
	}
	</script>
</body>
</html>